package com.cyan.note.security;

// import com.cyan.note.service.UserService;
import com.cyan.note.util.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;

/**
 * JWT认证过滤器
 * 用于验证HTTP请求中的JWT Token
 * 
 * @author ZhangzhenYu
 * @since 2025-01-13
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
    private final JwtUtil jwtUtil;
    // private final UserService userService; // 暂时移除避免循环依赖
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, 
                                    HttpServletResponse response, 
                                    FilterChain filterChain) throws ServletException, IOException {
        
        // 获取Authorization头
        final String authorizationHeader = request.getHeader("Authorization");
        
        String username = null;
        String jwt = null;
        
        // 检查Authorization头格式
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            try {
                username = jwtUtil.getUsernameFromToken(jwt);
                log.debug("JWT Token中提取的用户名: {}", username);
            } catch (Exception e) {
                log.warn("JWT Token解析失败: {}", e.getMessage());
            }
        }
        
        // 验证用户名和认证状态
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            
            try {
                // 验证Token
                if (jwtUtil.validateToken(jwt, username)) {
                    
                    // 从Token中提取用户信息
                    String role = jwtUtil.getRoleFromToken(jwt);
                    Long userId = jwtUtil.getUserIdFromToken(jwt);
                    Long shopId = jwtUtil.getShopIdFromToken(jwt);
                    
                    // 创建UserDetails对象
                    UserDetails userDetails = User.builder()
                            .username(username)
                            .password("")  // JWT验证不需要密码
                            .authorities(Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + role.toUpperCase())))
                            .build();
                    
                    // 创建认证Token
                    UsernamePasswordAuthenticationToken authToken = 
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    
                    // 设置额外的认证详情
                    authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    
                    // 在认证对象中添加自定义属性
                    CustomAuthenticationDetails customDetails = new CustomAuthenticationDetails();
                    customDetails.setUserId(userId);
                    customDetails.setUsername(username);
                    customDetails.setRole(role);
                    customDetails.setShopId(shopId);
                    authToken.setDetails(customDetails);
                    
                    // 设置到Security上下文
                    SecurityContextHolder.getContext().setAuthentication(authToken);
                    
                    log.debug("用户 {} 认证成功，角色: {}, 店铺ID: {}", username, role, shopId);
                    
                } else {
                    log.warn("JWT Token验证失败，用户名: {}", username);
                }
                
            } catch (Exception e) {
                log.error("JWT认证过程中出现异常: {}", e.getMessage());
            }
        }
        
        // 继续过滤链
        filterChain.doFilter(request, response);
    }
    
    /**
     * 自定义认证详情类
     * 用于在Security上下文中传递额外的用户信息
     */
    public static class CustomAuthenticationDetails {
        private Long userId;
        private String username;
        private String role;
        private Long shopId;
        
        // Getters and Setters
        public Long getUserId() { return userId; }
        public void setUserId(Long userId) { this.userId = userId; }
        
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        
        public String getRole() { return role; }
        public void setRole(String role) { this.role = role; }
        
        public Long getShopId() { return shopId; }
        public void setShopId(Long shopId) { this.shopId = shopId; }
    }
}